<?php

namespace backend\models;

use yii\base\Model;
use yii\web\UploadedFile;

/**
 * UploadForm is the model behind the upload form.
 */
class UploadForm extends Model
{
    /**
     * @var 单个文件上传对应属性;
     */
    public $single;

    /**
     * @var 多个文件对应的属性;
     */
    public $multiple;

    /**
     * @return array the validation rules.
     */
    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            [['single'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
            [['multiple'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg','maxFiles' => 4],
        ];
    }

    //单个文件上传对应方法
    public function upload()
    {
        if ($this->validate()) {
            $newName = 'uploads/' . $this->single->baseName . '.' . $this->single->extension;
            $this->single->saveAs($newName);
            return $newName;
        } else {
            return false;
        }
    }

    //多个文件上传对应方法
    public function uploadMultiple()
    {
        if ($this->validate())
        {
            foreach ($this->multiple as $file) {

                $newName = 'uploads/' . $file->baseName . '.' . $file->extension;
                $file->saveAs($newName);
            }
            return true;
        } else {
            return false;
        }
    }
}